package com.cl.unipay4j.wx.redpack;

import com.cl.unipay4j.core.IPayConfig;
import com.cl.unipay4j.core.Result;
import com.cl.unipay4j.core.UnipayConst;
import com.cl.unipay4j.core.redpack.IRedpackSend;
import com.cl.unipay4j.core.redpack.RedpackModel;
import com.cl.unipay4j.core.redpack.RedpackResponse;
import com.cl.unipay4j.core.util.MoneyUtil;
import com.cl.unipay4j.wx.AbstractWxPay;
import com.cl.unipay4j.wx.WxBizEnum;
import com.cl.unipay4j.wx.sdk.WXPayConstants;
import com.cl.unipay4j.wx.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信现金红包
 *
 * @author  siashan
 * @version V1.0.1
 **/
@Slf4j
public class WxPayRedpackSend extends AbstractWxPay implements IRedpackSend {


    /**
     * 构造方法
     */
    public WxPayRedpackSend() {
    }

    /**
     * 构造方法
     *
     * @param payConfig   支付配置
     */
    public WxPayRedpackSend(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 公众号红包发放
     *
     * @param model   发放红包实体
     * @return   请求结果
     */
    @Override
    public Result<RedpackResponse> sendRedpack(RedpackModel model) {
        log.info("WxPayRedpack => 订单{} 微信红包发放请求到达", model.getOutTradeNo());
        try {
            Map<String, String> r = initWxPay().sendRequest(wrapRedpackParam(model), WXPayConstants.MMPAYMKTTRANSFERS_SENDREDPACK_URL_SUFFIX, WxBizEnum.REDPACK, true);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            log.info("WxPayRedpack =>订单{} 微信红包发放请求返回报文:{}", model.getOutTradeNo(), r);
            // 通信标识判断
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                if (UnipayConst.SUCCESS.equals(r.get(WXPayConstants.RESULT_CODE))) {
                    log.info("WxPayRedpack =>订单{} 微信红包发放请求返回成功", model.getOutTradeNo());
                    return Result.tradeSuccess(wrapResp(r));
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxPayRedpack =>订单{} 微信红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), errCode, errCodeDes);
                    return Result.tradeFail(UnipayConst.FAIL,errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxPayRedpack =>订单{} 微信红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {
            log.warn("WxPayRedpack =>订单{} 微信红包发放发生异常", model.getOutTradeNo(), e);
        }
        return Result.exception();
    }

    /**
     * 发放裂变红包
     *
     * @param model   发放红包实体
     * @return        请求结果
     */
    @Override
    public Result<RedpackResponse> sendGroupRedpack(RedpackModel model) {
        log.info("WxPayRedpack => 订单{} 微信裂变红包发放请求到达", model.getOutTradeNo());
        try {
            Map<String, String> r = initWxPay().sendRequest(wrapGroupRedpackParam(model), WXPayConstants.MMPAYMKTTRANSFERS_SENDGROUPREDPACK_URL_SUFFIX,WxBizEnum.REDPACK, true);
            log.info("WxPayRedpack =>订单{} 微信裂变红包发放请求返回报文:{}", model.getOutTradeNo(), r);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                if (UnipayConst.SUCCESS.equals(r.get(WXPayConstants.RESULT_CODE))) {
                    log.info("WxPayRedpack =>订单{} 微信裂变红包发放请求返回成功", model.getOutTradeNo());
                    return Result.tradeSuccess(wrapResp(r));
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxPayRedpack =>订单{} 微信裂变红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), errCode, errCodeDes);
                    return Result.tradeFail(UnipayConst.FAIL,errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxPayRedpack =>订单{} 微信裂变红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {
            log.warn("WxPayRedpack =>订单{} 微信裂变红包发放发生异常", model.getOutTradeNo(), e);
        }
        return Result.exception();
    }

    /**
     * 发放小程序红包
     *
     * @param model  请求实体
     * @return       发放结果
     */
    @Override
    public Result<RedpackResponse> sendMiniprogramRedpack(RedpackModel model) {
        log.info("WxPayRedpack => 订单{} 微信小程序红包发放请求到达", model.getOutTradeNo());
        try {
            Map<String, String> r = initWxPay().sendRequest(wrapMiniprogramRedpackParam(model), WXPayConstants.MMPAYMKTTRANSFERS_SENDMINIPROGRAMHB_URL_SUFFIX,WxBizEnum.REDPACK, true);
            log.info("WxPayRedpack =>订单{} 微信小程序红包发放请求返回报文:{}", model.getOutTradeNo(), r);
            String returnCode = r.get(WXPayConstants.RETURN_CODE);
            if (UnipayConst.SUCCESS.equals(returnCode)) {
                if (UnipayConst.SUCCESS.equals(r.get(WXPayConstants.RESULT_CODE))) {
                    log.info("WxPayRedpack =>订单{} 微信小程序红包发放请求返回成功", model.getOutTradeNo());
                    return Result.tradeSuccess(wrapMiniResp(r));
                } else {
                    String errCode = r.get(WXPayConstants.ERR_CODE);
                    String errCodeDes = r.get(WXPayConstants.ERR_CODE_DES);
                    log.info("WxPayRedpack =>订单{} 微信小程序红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), errCode, errCodeDes);
                    return Result.tradeFail(UnipayConst.FAIL,errCode, errCodeDes);
                }
            } else {
                String returnMsg = r.get(WXPayConstants.RETURN_MSG);
                log.info("WxPayRedpack =>订单{} 微信小程序红包发放失败,错误代码:{},错误描述:{}", model.getOutTradeNo(), returnCode, returnMsg);
                return Result.returnFail(returnCode, returnMsg);
            }

        } catch (Exception e) {
            log.warn("WxPayRedpack =>订单{} 微信小程序红包发放发生异常", model.getOutTradeNo(), e);
        }
        return Result.exception();
    }

    /**
     * 小程序红包发放返回报文
     *
     * @param r             微信返回报文
     * @return              返回报文
     * @throws Exception
     */
    private RedpackResponse wrapMiniResp( Map<String, String> r) throws Exception {
        RedpackResponse response = wrapResp(r);

        Map<String, String> map = new HashMap<>(8);
        map.put("timeStamp", WXPayUtil.getCurrentTimestamp() + "");
        map.put("nonceStr", WXPayUtil.generateNonceStr());
        map.put("signType", "MD5");
        map.put("package",  URLEncoder.encode(r.get("package"),WXPayConstants.UTF_8));
        map.put("paySign", WXPayUtil.generateMiniRedpackSignature(map, wxPayConfig.getKey(), WXPayConstants.SignType.MD5));
        response.setBody(map);
        return response;
    }

    private RedpackResponse wrapResp( Map<String, String> r){
        RedpackResponse response = new RedpackResponse();
        response.setAmount(MoneyUtil.cent2Yuan(Integer.parseInt(r.get("total_amount"))));
        response.setOutTradeNo(r.get("mch_billno"));
        response.setTradeNo(r.get("send_listid"));
        return response;
    }


    /**
     * 包装微信红包请求参数
     *
     * @param model   红包请求实体
     * @return        包装后的请求参数
     */
    private Map<String, String> wrapRedpackParam(RedpackModel model) {
        Map<String, String> param = wrapParam(model);
        param.put("client_ip", model.getSpbillCreateIp());
        return param;
    }

    /**
     * 包装微信裂变红包请求参数
     *
     * @param model   红包请求实体
     * @return        包装后的请求参数
     */
    private Map<String, String> wrapGroupRedpackParam(RedpackModel model) {
        Map<String, String> param = wrapParam(model);
        param.put("amt_type", "ALL_RAND");
        return param;
    }

    private Map<String, String> wrapMiniprogramRedpackParam(RedpackModel model) {
        Map<String, String> param = wrapParam(model);
        param.put("notify_way", "MINI_PROGRAM_JSAPI");
        return param;
    }

    /**
     * 封装请求参数
     *
     * @param model 红包请求实体
     * @return   请求报文map
     */
    private Map<String, String> wrapParam(RedpackModel model) {
        Map<String, String> map = new HashMap<>();
        map.put("mch_billno", model.getOutTradeNo());
        map.put("send_name", model.getSendName());
        map.put("re_openid", model.getOpenid());
        map.put("total_num", String.valueOf(model.getTotalNum()));
        map.put("total_amount", String.valueOf(MoneyUtil.yuan2Cent(model.getTotalAmount())));
        map.put("wishing", model.getWishing());
        map.put("act_name", model.getActName());
        map.put("remark", model.getRemark());
        map.put("scene_id", model.getSceneId());
        return map;
    }
}
